24
Beginner’s Guide to Code Algorithms
24
Playing the game involves entering a “O” (nought) or a “X” (cross) in any of the
nine cells that are not already used.
For simplicity and pneumonic ease, the computer is always assumed to be playing
“O” and the human user “X”.
Now there is one more point to think about. Entering “X” requires a keystroke
from the keyboard as well as a mouse movement to pick the right cell. Wouldn’t it be
nice to just use the mouse instead? The good news is this is not so difficult. All we
need to do is create the code for a “double-click” for each of the nine TextBoxes as
shown below:
Private Sub TextBox1_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
If UserForm1.TextBox1 = "" Then
If UserForm1.TextBox10 = "" Then
UserForm1.TextBox1 = "X"
End If
Call TicTacToe
End If
End Sub
FIGURE 2.23 Code in TextBox1.
TextBox10 is the message bar—it is only populated when the game is won or drawn.
Hence this is checked before an “X” is placed in the required cell.
Tic Tac Toe is the program that has the rest of the logic.
This is executed every time a user double-clicks in the middle of a new game.
The code for this subroutine is below. We will dive into each aspect of this code:
• How do we maintain the score?
• How does the computer know which cells are still empty?
• How does the computer determine the best move?
The following lines are required so that they can be accessed from any function. If
we do not do this, these variables are only visible in the function they are defined in.
Public WinTag As Variant
Public Factor(3) As Variant
Public XScore As Double
Public OScore As Double
Now let us write the main code where the scoring lines are highlighted.